package com.cyy.dyeing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.dyeing.common.*;
import com.cyy.dyeing.dto.GroupDto;
import com.cyy.dyeing.dto.ProcessNode;
import com.cyy.dyeing.exception.BusinessException;
import com.cyy.dyeing.model.Group;
import com.cyy.dyeing.model.Plan;
import com.cyy.dyeing.dto.PlanDto;
import com.cyy.dyeing.service.ProcessNodeService;
import com.cyy.dyeing.service.ProcessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.ws.rs.HEAD;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: cyy
 * @Date: 2024/7/27
 */
@RestController
@RequestMapping("/process")
public class ProcessController {
    @Autowired
    private ProcessService processService;

    @Autowired
    private ProcessNodeService processNodeService;

    @Autowired
    private  BaseApi baseApi;

    /**
     * 条件查询
     * @param planDto
     * @return
     */
    @GetMapping("/plan")
    public Result getPlanList(PlanDto planDto){
        List<Plan> planList = processService.findPlanList(planDto);
        return Result.ok(planList);
    }


    /**
     * 添加组别
     * @param group
     * @return
     */
    @PostMapping("/group")
    public Result groupAdd(@RequestBody Group group,
                           @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        // 设置操作信息
        SimpleDateFormat groupIdFmt = new SimpleDateFormat("yyyyMMdd-HHmmss-SSS");
        AtomicInteger no = new AtomicInteger(0);
        Date now = new Date();
        String group_id = groupIdFmt.format(now)+"-"+no.incrementAndGet();
        group.setGroup_id(group_id);
        processService.save(group);
        //个人信息
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        //向流程节点添加数据
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_date(now);
        processNode.setPn_per(per);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_ToGroup_1000.getCode());
        processNode.setPn_curr(true);
        processNode.setPn_status(true);
        processNode.setPn_id(UUID.randomUUID().toString().replace("-", ""));
        processNodeService.save(processNode);
        return Result.ok();
    }

    /**
     * 确定投坯
     * @param group_id
     * @return
     */
    @PutMapping("/group/done/{group_id}")
    public Result groupDone(@PathVariable String group_id,
                            @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId()+"|"+currentUser.getUsername();
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_date(new Date());
        processNode.setPn_per(per);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DoneGroup_1010.getCode());
        processNode.setPn_curr(true);
        processNode.setPn_status(true);
        addProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        return Result.ok();
    }

    private void addProcessNode(ProcessNode pn, int processDefCls){
        pn.setPn_id(UUID.randomUUID().toString().replace("-", ""));
        if(pn.getPn_curr()){//判断是否当前流程
            if(processDefCls == 1)
                processNodeService.updateAllGroupProcessNodeCurrFalse(pn.getGroup_id(), processDefCls);
            else if(processDefCls == 2)
                ;
            else if (processDefCls == 3) {
                ;
            }
            if(processDefCls == 1);

        }
        ProcessNode node = null;
        if(processDefCls == 1){
            processNodeService.updateAllGroupProcessNodeCurrFalse(pn.getGroup_id(), processDefCls);
        }
        if(node == null){//新增
            processNodeService.save(pn);
        }else{//更新
            pn.setPn_id(node.getPn_id());
            processNodeService.updateProcessNode(pn);
        }
    }

    /**
     * 投坯删除
     * @param group_id
     * @return
     */
    @DeleteMapping("/group/{group_id}")
    public Result groupDel(@PathVariable String group_id){
        LambdaQueryWrapper<ProcessNode> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProcessNode::getGroup_id, group_id);
        wrapper.eq(ProcessNode::getPd_id, ProcessDefEnum.CLS_GROUP_DEF_ToGroup_1000);
        wrapper.eq(ProcessNode::getPn_status, 1);
        wrapper.eq(ProcessNode::getPn_curr, 1);
        ProcessNode one = processNodeService.getOne(wrapper);
        if(one == null){
            throw new BusinessException("分组数据非带投坯状态，不能删除");
        }
        //删除节点
        LambdaQueryWrapper<ProcessNode> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ProcessNode::getGroup_id, group_id);
        processNodeService.remove(wrapper);
        //删除组别
        LambdaQueryWrapper<Group> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        groupLambdaQueryWrapper.eq(Group::getGroup_id, group_id);
        processService.remove(groupLambdaQueryWrapper);
        return Result.ok();
    }


    /**
     * 流程数据信息
     * @return
     */
    @GetMapping("/process-def")
    public Result processDefList(){
        return baseApi.processDef();
    }

    /**
     * 前处理查询
     * @param groupDto
     * @return
     */
    @GetMapping("/pretreat")
    public Result groupPreteatList(GroupDto groupDto){
        List<Group> list = processService.findGroupList(groupDto);
        Page<Group> groupPage = new Page<>(groupDto.getPageNum(), groupDto.getPageSize());
        groupPage.setRecords(list);
        return Result.ok(groupPage);
    }

    /**
     * 前处理——录入数量
     * @param group_id
     * @param retreat_num
     * @param token
     * @return
     */
    @PutMapping("/pretreat/save/{group_id}/{retreat_num}")
    public Result savePretreat(@PathVariable String group_id,
                               @PathVariable Integer retreat_num,
                               @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId()+"|"+currentUser.getUsername();
        if(retreat_num == null || retreat_num < 1){
            throw new BusinessException("请录入正确产量");
        }
        ProcessNode pn = new ProcessNode();
        pn.setGroup_id(group_id);
        pn.setPn_date(new Date());
        pn.setPn_per(per);
        pn.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DonePretreatment_1020.getCode());
        pn.setPn_curr(false);
        pn.setPn_status(false);
        ProcessNode pNode = processNodeService.findProcessNodeByGroupIdAndPdId(pn);
        if(pNode == null){
            //不存在流程节点
            addProcessNode(pn, ProcessDefEnum.CLS_GROUP.getCode());
        }
        processService.updateGroupNumOfGroup(group_id, "pretreat_num", retreat_num);
        return Result.ok();
    }

    /**
     * 前处理 确认
     * @param group_id
     * @param token
     * @return
     */
    @PutMapping("/pretreat/done/{group_id}")
    public Result groupDoPretreat(@PathVariable String group_id,
                                  @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId()+"|"+currentUser.getUsername();
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DonePretreatment_1020.getCode());
        processNode.setPn_date(new Date());
        processNode.setPn_per(per);
        processNode.setPn_status(true);
        processNode.setPn_curr(true);
        ProcessNode one = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(one == null){
            throw new BusinessException("请先录入产量");
        }
        processNodeService.updateProcessNode(processNode,ProcessDefEnum.CLS_GROUP.getCode());
        return Result.ok();
    }

    /**
     * 染色-【查询】
     * @param groupDto
     * @return
     */
    @GetMapping("/dye")
    public Result groupDyeList(GroupDto groupDto){
        groupDto.setAcceptedProTypes(new Integer[]{2, 4});
        Page<Group> groupPage = new Page<>(groupDto.getPageNum(), groupDto.getPageSize());
        List<Group> groupList = processService.findGroupList(groupDto);
        groupPage.setRecords(groupList);
        return Result.ok(groupPage);
    }

    /**
     * 染色 —— 数量
     * @param group_id
     * @param dye_num
     * @param token
     * @return
     */
    @PutMapping("/dye/save/{group_id}/{dye_num}")
    public Result groupSaveDye(@PathVariable String group_id,
                               @PathVariable Integer dye_num,
                               @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        if(dye_num == null || dye_num < 1){
            throw  new BusinessException("请输入正确的产量");
        }
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_per(per);
        processNode.setPn_date(new Date());
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DoneDye_1030.getCode());
        processNode.setPn_status(false);
        processNode.setPn_curr(false);
        ProcessNode pn = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(pn == null){
            addProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        }
        processService.updateGroupNumOfGroup(pn.getGroup_id(), "dye_num", dye_num);
        return Result.ok();
    }

    /**
     * 染色 —— 确认
     * @param group_id
     * @param token
     * @return
     */
    @PutMapping("/dye/done/{group_id}")
    public Result groupDoDye(@PathVariable String group_id,
                             @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_date(new Date());
        processNode.setPn_per(per);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DoneDye_1030.getCode());
        processNode.setPn_curr(true);
        processNode.setPn_status(true);
        ProcessNode pn = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(pn == null){
            throw new BusinessException("请先输入产量");
        }
        processNodeService.updateProcessNode(pn, ProcessDefEnum.CLS_GROUP.getCode());
        return Result.ok();
    }

    /**
     * 印花 —— 确认
     * @param groupDto
     * @return
     */
    @GetMapping("/print")
    public Result groupPrintList(GroupDto groupDto){
        groupDto.setAcceptedProTypes(new Integer[]{3, 4});
        groupDto.setPrint(true);
        List<Group> list = processService.findGroupList(groupDto);
        Page<Group> groupPage = new Page<>(groupDto.getPageNum(), groupDto.getPageSize());
        groupPage.setRecords(list);
        return Result.ok(groupPage);
    }

    /**
     * 印花数量录入
     * @param group_id
     * @param print_num
     * @param token
     * @return
     */
    @PutMapping("/print/save/{group_id}/{print_num}")
    public Result groupSavePrint(@PathVariable String group_id,
                                 @PathVariable Integer print_num,
                                 @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|"  + currentUser.getUsername();
        if(print_num == null || print_num < 1){
            throw new BusinessException("请正确输入印花数量");
        }
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_per(per);
        processNode.setPn_date(new Date());
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DonePrint_1040.getCode());
        processNode.setPn_curr(false);
        processNode.setPn_status(false);
        ProcessNode one = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(one == null){
            addProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        }
        processService.updateGroupNumOfGroup(group_id, "print_num", print_num);
        return Result.ok();
    }

    /**
     * 印花  —— 确认
     * @return
     */
    @PutMapping("/print/done/{group_id}")
    public Result groupDoPrint(@PathVariable String group_id,
                               @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_per(per);
        processNode.setPn_date(new Date());
        processNode.setPn_curr(true);
        processNode.setPn_status(true);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DonePrint_1040.getCode());
        ProcessNode one = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(one == null){
            throw new BusinessException("请先录入产量!");
        }
        processNodeService.updateProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        return Result.ok();
    }

    /**
     * 整理模块
     * @return
     */
    @GetMapping("/arrange")
    public Result groupArrangeList(GroupDto groupDto){
        groupDto.setArrange(true); // 请求数据为整理模块
        List<Group> list = processService.findGroupList(groupDto);
        Page<Group> groupPage = new Page<>(groupDto.getPageNum(), groupDto.getPageSize());
        groupPage.setRecords(list);
        return Result.ok(groupPage);
    }

    /**
     * 整理模块 —— 录入
     * @param group_id
     * @param arrange_num
     * @param token
     * @return
     */
    @PutMapping("/arrange/save/{group_id}/{arrange_num}")
    public Result groupSaveArrange(@PathVariable String group_id,
                                   @PathVariable Integer arrange_num,
                                   @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        if(arrange_num == null || arrange_num < 1){
            throw new BusinessException("请输入正确的产量！");
        }
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_per(per);
        processNode.setPn_date(new Date());
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DoneArrange_1050.getCode());
        processNode.setPn_curr(false);
        processNode.setPn_status(false);
        ProcessNode one = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(one == null){
            addProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        }
        processService.updateGroupNumOfGroup(group_id, "arrange_num", arrange_num);
        return Result.ok();
    }

    /**
     * 整理模块  —— 确认
     * @return
     */
    @PutMapping("/arrange/done/{group_id}")
    public Result groupDoArrange(@PathVariable String group_id,
                               @RequestHeader(DyeingConstants.HEADER_USER_TOKEN)String token){
        CurrentUser currentUser = TokenUtils.getCurrentUser(token);
        String per = currentUser.getUserId() + "|" + currentUser.getUsername();
        ProcessNode processNode = new ProcessNode();
        processNode.setGroup_id(group_id);
        processNode.setPn_per(per);
        processNode.setPn_date(new Date());
        processNode.setPn_curr(true);
        processNode.setPn_status(true);
        processNode.setPd_id(ProcessDefEnum.CLS_GROUP_DEF_DoneArrange_1050.getCode());
        ProcessNode one = processNodeService.findProcessNodeByGroupIdAndPdId(processNode);
        if(one == null){
            throw new BusinessException("请先录入产量!");
        }
        processNodeService.updateProcessNode(processNode, ProcessDefEnum.CLS_GROUP.getCode());
        return Result.ok();
    }

}
